package com.lhkj.ct.base.utils.file.word;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.lhkj.ct.base.exception.SystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.OutputStream;

/**
 *
 */
public class AsposeWordsUtil {

    private static Logger logger = LoggerFactory.getLogger(AsposeWordsUtil.class);

    /**
     * 获取license
     *
     * @return
     */
    public static boolean getLicense() {
        boolean result = false;
        try {
//            Class<?> aClass = Class.forName("com.aspose.words.zzXyu");
//            java.lang.reflect.Field zzZXG = aClass.getDeclaredField("zzZXG");
//            zzZXG.setAccessible(true);
//            java.lang.reflect.Field modifiersField = zzZXG.getClass().getDeclaredField("modifiers");
//            modifiersField.setAccessible(true);
//            modifiersField.setInt(zzZXG, zzZXG.getModifiers() & ~Modifier.FINAL);
//            zzZXG.set(null,new byte[]{76, 73, 67, 69, 78, 83, 69, 70});
            InputStream inputStream = AsposeWordsUtil.class.getResourceAsStream("/license.xml");
            License aposeLic = new com.aspose.words.License();
            aposeLic.setLicense(inputStream);
            result = true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * word转换为pdf
     * @param wordInput word文件输入流
     * @param pdfOutput pdf文件输出流
     * @throws Exception
     */
    public static void wordToPdf(InputStream wordInput, OutputStream pdfOutput) throws Exception {
        if (!getLicense()) {
            throw new SystemException("PDF生成授权凭证无效");
        }
        //通过aspose-words.jar中的类转换文件
        Document doc = new Document(wordInput);
        doc.save(pdfOutput, SaveFormat.PDF);
    }

}
